$(function() {
	userDatatableSource.init();
	pageSource.init();
});

var userDatatable;
var genderOptions = [{id:"1",text:"男"},{id:"2",text:"女"},{id:"0",text:"未知"}];
var userTypeOptions =[{id:"0",text:"系统用户"},{id:"1",text:"航司用户"}];
/**
 * 表格列定义
 * 
 * @type {*[]}
 */
var tableColumns = [{
		field: "id",
		title: "#",
		width: 20,
		textAlign: 'center',
		selector: {
			class: "m-checkbox--solid m-checkbox--brand"
		}
	},
	{
		field: "name",
		title: "用户名",
		textAlign: 'center',
		sortable: false,
		width: 80,
	},
	{
		field: "code",
		title: "用户编码",
		textAlign: 'center',
		sortable: false,
		width: 60,
	},
	{
		field: "gender",
		title: "性别",
		textAlign: 'center',
		sortable: false,
		width: 40,
		template:function(row){
			var genderType ="";
			switch(row.gender){
	    	   case 0:
	    		   genderType="未知";
	    		   break;
	    	   case 1:
	    		   genderType="男";
	    		   break;
	    	   case 2:
	    		   genderType="女";
	    		   break;
	    	   default:
	    		   genderType="未定义";
	    		 }
	    	 return genderType;
	    	}
	},
	{
		field: "telephone",
		title: "座机",
		textAlign: 'center',
		sortable: false,
		width: 50,
	},
	{
		field: "mobile",
		title: "手机号码",
		textAlign: 'center',
		sortable: false
	},
	{
		field: "email",
		title: "邮箱",
		textAlign: 'center',
		sortable: false
	},
	{
		field: "userType",
		title: "用户类型",
		textAlign: 'center',
		sortable: false,
		template:function(row){
			var _userType ="";
			switch(row.userType){
	    	   case 0:
	    		   _userType="系统用户";
	    		   break;
	    	   case 1:
	    		   _userType="航司用户";
	    		   break;
	    	   default:
	    		   _userType="未定义";
	    		 }
	    	 return _userType;
	    	}
	},

	{
		field: "airlineCode",
		title: "航司",
		textAlign: 'center',
		sortable: false,
		width: 50
	},
	{
		field: "actions",
		textAlign: 'center',
		title: "操作",
		sortable: !1,
		overflow: "visible",
		template: function(row) {
			var btn="";
			if(row.id != "1"){
				btn= getColumnButton({
					clazz: 'm-btn--hover-accent editBtn',
					title: '编辑',
					icon: 'la la-edit',
					id: row.id,
					name: row.name
				});
//				if(row.userType == 1){
//				btn = btn + getColumnButton({
//						clazz: 'm-btn--hover-brand airlineBtn',
//						title: '航司',
//						icon: 'fa fa-plane',
//						id: row.id,
//						name: row.airlineCode
//					});
//				}
				btn = btn + getColumnButton({
					clazz: 'm-btn--hover-danger deleteBtn',
					title: '删除',
					icon: 'la la-trash',
					id: row.id,
					name: row.name
				});
			}
			return btn;

		}
	}
];

/**
 * 初始化表格定义
 */
var userDatatableSource = {
		init: function (){
			userDatatable = $("#user_data").mDatatable(getMDatatableOption('list', {
					isDelete: 0,
					sortName: 'createTime'
			}, tableColumns));
		},
		deleteById: function (id){
			$.hcPostAjax({
				showLoad: true,
				msgPrefix: '用户删除失败：',
				url: '../user/deleteByIds',
				data: {
					ids: id
				},
				success: function(json) {
					layer.msg('用户删除成功！', {
						icon: 1,time:1500
					}, function() {
						userDatatable.reload();
					});
				}
			});
		}
}
var pageSource ={
		init:function(){
			
			loadAirlineSelector();
			
			// form 表单校验
			form.verify({
				  username: function(value, item){ // value：表单的值、item：表单的DOM对象
				    if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
				      return '用户名不能有特殊字符';
				    }
				    if(/(^\_)|(\__)|(\_+$)/.test(value)){
				      return '用户名首尾不能出现下划线\'_\'';
				    }
				    if(/^\d+\d+\d$/.test(value)){
				      return '用户名不能全为数字';
				    }
				  }
				  // 我们既支持上述函数式的方式，也支持下述数组的形式
				  // 数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
				  ,pass: [
				    /^[\S]{6,12}$/
				    ,'密码必须6到12位，且不能出现空格'
				  ] 
				});      
			/**
			 * 查询
			 */
			$("#m_search").on("click", function() {
				var param = {
					isDelete: 0,
					name: $.trim($("#name").val()),
					code: $.trim($("#code").val()),
					mobile: $.trim($("#mobile").val()),
					airlineCode:$.trim($("#airlineCode").val())
				};
				queryMDatatable(userDatatable, param);
			});

			/**
			 * 单个删除
			 */
			$("#user_data").on("click", ".deleteBtn", function() {
				var id = $(this).data("id");
				var name = $(this).data("name");
				layer.confirm('确定删除该用户<font color="red">[' + name + ']</font>？', {
					icon: 3,
					title: '提示',
					btn: ['确定', '取消'] // 按钮
				}, function(index) {
					userDatatableSource.deleteById(id);
				}, function(index) {
					layer.close(index);
				});
			});

			/**
			 * 修改数据页面
			 */
			$("#user_data").on("click", ".editBtn", function() {
				var id = $(this).data("id");
				openEditUser('修改用户', id);
			});
		}
}




/**
 * @param title
 * @param obj
 */
function openEditUser(title, id) {
	var msg = isEmpty(id) ? "新增" :"编辑";
	layer.open({
		title: title,
		type: 1,
		maxmin: true,
		area: ['60%', '100%'],
		shadeClose: true,
		scrolling:false,
		content: $("#editHtml").html(),
		success: function(layero, index) {
            $.hcPostAjax({
                url: basePath + "/airline/allAirline",
                success: function(data) {
                    var airlineOptions= [];
                    $.each(data, function(i) {
                        airlineOptions.push({id: data[i].code + "", text: data[i].shortName + "("+data[i].code+")"});
                    });
                    $("#user-form select[name= airlineCode]").val('').select2({
                        placeholder:"请选择航司",
                        data:airlineOptions,
                        width:'425px',
                        allowClear:true
                    });
                }
            });
			laytpl($("#gender-select-template").html()).render({list: genderOptions}, function(html){
                $("#user-form select[name=gender]").append(html);
             });
			$("#user-form select[name=gender]").selectpicker();
			
			laytpl($("#userType-select-template").html()).render({list: userTypeOptions}, function(html){
                $("#user-form select[name= userType]").append(html);
             });
			$("#user-form select[name= userType]").selectpicker();
			
			if(!isEmpty(id)) {
				
				renderFormData("#user-form", getDetail(id));
				// 编辑时不让修改密码
				$("#user-form div.password").hide();
				
				var _userType = $("#user-form select[name= userType]").val();
				if(_userType == "0"){
					$("#edit-airlineCode-div").hide();
				}else{
					$("#edit-airlineCode-div").show();
				}
			}
			$("#user-form select[name= userType]").on("change",function(){
				var _userType = $("#user-form select[name= userType]").val();
				if(_userType == "0"){
					$("#edit-airlineCode-div").hide();
				}else{
					$("#edit-airlineCode-div").show();
				}
			})
			
			/**
			 * 保存规则
			 */
			$("#edit_yes").on("click", function() {
				if(!isEmpty(id)){
					$("input[name ='password']").removeAttr("required").removeAttr("lay-verify").removeAttr("lay-verType");
				}
				
				form.on('submit(save_user)', function(data) {
					/**
					 * 保存用户
					 * 
					 * @param msg
					 */
					var param = getFormData("#user-form");
					param.password = $("#user-form input[name ='password']").val();
					if(!isEmpty(id)){
						param.id=id;
						// 不然修改密码
						param.password='';
					}
					
					
					
					if(param.userType =="0"){
						param.airlineCode='';
					}
					
					if(!isEmpty(param.email)){
						if (!new RegExp("^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$").test(param.email)) {
							layer.msg("邮箱格式不正确",{icon: 5,anim:6,time:1000});
							return ;
			            }
					}
					

					if(!isEmpty(param.mobile)){
						if (!/^[1][3,4,5,7,8][0-9]{9}$/.test(param.mobile)) {
							layer.msg("手机号格式不正确",{icon: 5,anim:6,time:1000});
							return ;
				            }
					}
					
					
				
						$.hcPostAjax({
							showLoad: true,
							msgPrefix:msg+ "出错：",
							url: '../user/addOrUpdate',
							data: param,
							success: function(data) {
								layer.msg(msg + '成功！', {
									icon: 1,time:1500
								}, function() {
									userDatatable.reload();
									layer.closeAll();
								});
							}
						});

				});
			});

			/**
			 * 取消修改
			 */
			$("#edit_cancle").on("click", function() {
				layer.closeAll();
			});
		}
	});
}

/**
 * 批量删除
 */
function batchDel() {
	var ids = getMDatatableSelectedIds(userDatatable);
	if(ids.length === 0) {
		layer.msg('请勾选要删除的用户信息！', {
			icon: 0
		});
		return;
	}

	var names = getMDatatableSelectedColumns(userDatatable, "name");
	layer.confirm('确定批量删除该用户<font color="red">[' + names + ']</font>？', {
		icon: 3,
		title: '提示',
		btn: ['确定', '取消'] // 按钮
	}, function() {
		userDatatableSource.deleteById(ids.join(','));
	}, function(index) {
		layer.close(index);
	});
}

function getDetail(id) {
	var oldData;
	$.hcPostAjax({
		url: basePath + "/user/detail",
		data: {
			id: id
		},
		async: false,
		success: function(data) {
			oldData = data;
		}
	})
	return oldData;
}

function loadAirlineSelector(){
	$.hcPostAjax({
		url: basePath + "/airline/allAirline",
		success: function(data) {
            var airlineOptions= [];
			$.each(data, function(i) {
				airlineOptions.push({id: data[i].code + "", text: data[i].shortName + "("+data[i].code+")"});
			});
            $("#airlineCode").val('').select2({
                placeholder:"请选择航司",
                data:airlineOptions,
                allowClear:true
            });
		}
	})
}

function exportExcel(type) {
	var param = {
			isDelete: 0,
			name: $.trim($("#name").val()),
			code: $.trim($("#code").val()),
			mobile: $.trim($("#mobile").val()),
			airlineCode:$.trim($("#airlineCode").val())
		};
    var url = basePath + "/export/user/" + type;
    location.href = buildExportUrl(url, param);
}

function exportPirnt(){
	var param = {
			isDelete: 0,
			name: $.trim($("#name").val()),
			code: $.trim($("#code").val()),
			mobile: $.trim($("#mobile").val()),
			airlineCode:$.trim($("#airlineCode").val())
		};
    var url = basePath + "/print/user";
    commonPrint(param,url);
}